package com.ruoyi.combat.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.combat.domain.CombatMethod;
import com.ruoyi.combat.domain.MethodUseLog;
import com.ruoyi.combat.service.ICombatMethodService;
import com.ruoyi.combat.service.IMethodUseLogService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.*;

@Component
@Slf4j
public class MethodUseUtils {

    @Autowired
    private ICombatMethodService iCombatMethodService;
    @Autowired
    private IMethodUseLogService iMethodUseLogService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据算法id调用算法，立即返回结果
     *
     * @param methodId
     * @return
     */
    public Map<String, Object> methodUseLogs(Long methodId, String requestBody) {
        CombatMethod combatMethod = iCombatMethodService.selectCombatMethodById(methodId);
        if (combatMethod != null) {
            String url = combatMethod.getMethodUrl();
            if (StringUtils.isNotBlank(url) && "POST".equals(combatMethod.getMethodType())) {
                //发送post请求，并打印结果，以String类型接收响应结果JSON字符串
                log.info("URL：{}", url);
                log.info("data：{}", requestBody);
                String post = HttpUtil.post(url, requestBody);
                log.info("result：{}", post);
                LinkedHashMap bean = null;
                try {
                    bean = JSONUtil.toBean(post, LinkedHashMap.class);
                } catch (Exception e) {

                }
                try {
                    MethodUseLog methodUseLog = new MethodUseLog();
                    methodUseLog.setMethodId(methodId);
                    methodUseLog.setMethodParam(requestBody);
                    methodUseLog.setMethodName(combatMethod.getMethodName());
//                    methodUseLog.setUserId(SecurityUtils.getUserId());
                    methodUseLog.setMethodResult(post);
                    methodUseLog.setCreateTime(new Date());
                    iMethodUseLogService.insertMethodUseLog(methodUseLog);
                    Long methodNum = combatMethod.getMethodNum();
                    if (methodNum == null) {
                        methodNum = 0L;
                    }
                    methodNum = methodNum + 1;
                    combatMethod.setMethodNum(methodNum);
                    iCombatMethodService.updateCombatMethod(combatMethod);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bean;
            } else if (StringUtils.isNotBlank(url) && "GET".equals(combatMethod.getMethodType())) {
                //发送post请求，并打印结果，以String类型接收响应结果JSON字符串
//                String get = HttpUtil.get(url);
                HttpRequest request = HttpRequest.get(url)
                        .header("Content-Type", "application/json");
                request.body(requestBody);
                String get = request.execute().body();
                LinkedHashMap bean = JSONUtil.toBean(get, LinkedHashMap.class);
                try {
                    MethodUseLog methodUseLog = new MethodUseLog();
                    methodUseLog.setMethodId(methodId);
                    methodUseLog.setMethodParam(requestBody);
                    methodUseLog.setMethodName(combatMethod.getMethodName());
                    methodUseLog.setUserId(SecurityUtils.getUserId());
                    methodUseLog.setMethodResult(get);
                    methodUseLog.setCreateTime(new Date());
                    iMethodUseLogService.insertMethodUseLog(methodUseLog);
                    Long methodNum = combatMethod.getMethodNum();
                    if (methodNum == null) {
                        methodNum = 0L;
                    }
                    methodNum = methodNum + 1;
                    combatMethod.setMethodNum(methodNum);
                    iCombatMethodService.updateCombatMethod(combatMethod);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bean;
            }
            return null;
        }
        return null;
    }
    public Map<String, Object> methodUseLogs(Long methodId, String requestBody,String Content_Type) {
        CombatMethod combatMethod = iCombatMethodService.selectCombatMethodById(methodId);
        if (combatMethod != null) {
            String url = combatMethod.getMethodUrl();
            if (StringUtils.isNotBlank(url)) {
//                String post = HttpUtils.sendPostJson(url, requestBody);
                String post = HttpUtil.post(url, requestBody);
                Map bean = null;
                try {
                    bean = JSONUtil.toBean(post, Map.class);
                } catch (Exception e) {
//                    throw new RuntimeException(e);
                }
                try {
                    MethodUseLog methodUseLog = new MethodUseLog();
                    methodUseLog.setMethodId(methodId);
                    methodUseLog.setMethodParam(requestBody);
                    methodUseLog.setMethodName(combatMethod.getMethodName());
                    methodUseLog.setUserId(SecurityUtils.getUserId());
                    methodUseLog.setMethodResult(post);
                    methodUseLog.setCreateTime(new Date());
                    iMethodUseLogService.insertMethodUseLog(methodUseLog);
                    Long methodNum = combatMethod.getMethodNum();
                    if (methodNum == null) {
                        methodNum = 0L;
                    }
                    methodNum = methodNum + 1;
                    combatMethod.setMethodNum(methodNum);
                    iCombatMethodService.updateCombatMethod(combatMethod);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bean;
            }
            return null;
        }
        return null;
    }
    public Map<String, Object> methodUseLogs1(Long methodId, String requestBody,String Content_Type) {
        CombatMethod combatMethod = iCombatMethodService.selectCombatMethodById(methodId);
        if (combatMethod != null) {
            String url = combatMethod.getMethodUrl();
            if (StringUtils.isNotBlank(url)) {
                String post = HttpUtils.sendPostJson(url, requestBody);
//                String post = HttpUtil.post(url, requestBody);
                Map bean = null;
                try {
                    bean = JSONUtil.toBean(post, Map.class);
                } catch (Exception e) {
//                    throw new RuntimeException(e);
                }
                try {
                    MethodUseLog methodUseLog = new MethodUseLog();
                    methodUseLog.setMethodId(methodId);
                    methodUseLog.setMethodParam(requestBody);
                    methodUseLog.setMethodName(combatMethod.getMethodName());
                    methodUseLog.setUserId(SecurityUtils.getUserId());
                    methodUseLog.setMethodResult(post);
                    methodUseLog.setCreateTime(new Date());
                    iMethodUseLogService.insertMethodUseLog(methodUseLog);
                    Long methodNum = combatMethod.getMethodNum();
                    if (methodNum == null) {
                        methodNum = 0L;
                    }
                    methodNum = methodNum + 1;
                    combatMethod.setMethodNum(methodNum);
                    iCombatMethodService.updateCombatMethod(combatMethod);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return bean;
            }
            return null;
        }
        return null;
    }

    public String methodUseLogs(Long methodId, Map data,Long userId) {
        CombatMethod combatMethod = iCombatMethodService.selectCombatMethodById(methodId);
        if (combatMethod != null) {
            String url = combatMethod.getMethodUrl();
            if (StringUtils.isNotBlank(url)) {
                //发送post请求，并打印结果，以String类型接收响应结果JSON字符串
//                HttpResponse response = HttpRequest.post(url)
//
//                        .setConnectionTimeout(5000)
//                        .setReadTimeout(5000)
//                        .execute();
//
//                if (response.isOk()) {
//                    String body = response.body();
//                    System.out.println("响应内容：" + body);
//                } else {
//                    System.out.println("请求失败，状态码：" + response.getStatus());
//                }

                String post = HttpUtil.post(url, data);
//                List<LinkedHashMap> list = JSONUtil.toList(post, LinkedHashMap.class);
                try {
                    MethodUseLog methodUseLog = new MethodUseLog();
                    methodUseLog.setMethodId(methodId);
                    methodUseLog.setMethodParam(JSONUtil.toJsonStr(data));
                    methodUseLog.setMethodName(combatMethod.getMethodName());
                    methodUseLog.setUserId(userId);
                    methodUseLog.setMethodResult(post);
                    methodUseLog.setCreateTime(new Date());
                    iMethodUseLogService.insertMethodUseLog(methodUseLog);
                    Long methodNum = combatMethod.getMethodNum();
                    if (methodNum == null) {
                        methodNum = 0L;
                    }
                    methodNum = methodNum + 1;
                    combatMethod.setMethodNum(methodNum);
                    iCombatMethodService.updateCombatMethod(combatMethod);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return post;
            }
            return null;
        }
        return null;
    }

    public String methodUseLogs(Long methodId, Map<String, Object> data,String userName, String password) {
        // http post请求，给请求头添加参数
        String authCredentials = userName + ":" + password;
        String encodedAuth = Base64.getEncoder().encodeToString(authCredentials.getBytes(StandardCharsets.UTF_8));
        String basicAuthHeader = "Basic " + encodedAuth;
        CombatMethod combatMethod = iCombatMethodService.selectCombatMethodById(methodId);
        if (combatMethod != null) {
            String url = combatMethod.getMethodUrl();
            if (StringUtils.isNotBlank(url)) {
                if (ObjectUtil.isNotNull(data)) {
                    HttpResponse post = HttpRequest.post(url)
                            .header("Authorization", basicAuthHeader)
                            .body(JSONUtil.toJsonStr(data))
                            .execute();
                    try {
                        MethodUseLog methodUseLog = new MethodUseLog();
                        methodUseLog.setMethodId(methodId);
                        methodUseLog.setMethodParam(JSONUtil.toJsonStr(data));
                        methodUseLog.setMethodName(combatMethod.getMethodName());
                        methodUseLog.setMethodResult(post.body());
                        methodUseLog.setCreateTime(new Date());
                        iMethodUseLogService.insertMethodUseLog(methodUseLog);
                        Long methodNum = combatMethod.getMethodNum();
                        if (methodNum == null) {
                            methodNum = 0L;
                        }
                        methodNum = methodNum + 1;
                        combatMethod.setMethodNum(methodNum);
                        iCombatMethodService.updateCombatMethod(combatMethod);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return post.body();
                } else {
                    HttpResponse post = HttpRequest.post(url)
                            .header("Authorization", basicAuthHeader)
                            .execute();
                    try {
                        MethodUseLog methodUseLog = new MethodUseLog();
                        methodUseLog.setMethodId(methodId);
                        methodUseLog.setMethodParam(JSONUtil.toJsonStr(data));
                        methodUseLog.setMethodName(combatMethod.getMethodName());
                        methodUseLog.setMethodResult(post.body());
                        methodUseLog.setCreateTime(new Date());
                        iMethodUseLogService.insertMethodUseLog(methodUseLog);
                        Long methodNum = combatMethod.getMethodNum();
                        if (methodNum == null) {
                            methodNum = 0L;
                        }
                        methodNum = methodNum + 1;
                        combatMethod.setMethodNum(methodNum);
                        iCombatMethodService.updateCombatMethod(combatMethod);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return post.body();
                }
            }
            return null;
        }
        return null;
    }

    public String methodUseLogs(Long methodId, List<Map<String, Object>> data,String userName, String password) {
        // http post请求，给请求头添加参数
        String authCredentials = userName + ":" + password;
        String encodedAuth = Base64.getEncoder().encodeToString(authCredentials.getBytes(StandardCharsets.UTF_8));
        String basicAuthHeader = "Basic " + encodedAuth;
        CombatMethod combatMethod = iCombatMethodService.selectCombatMethodById(methodId);
        if (combatMethod != null) {
            String url = combatMethod.getMethodUrl();
            if (StringUtils.isNotBlank(url)) {
                if (ObjectUtil.isNotNull(data)) {
                    HttpResponse post = HttpRequest.post(url)
                            .header("Authorization", basicAuthHeader)
                            .body(JSONUtil.toJsonStr(data))
                            .execute();
                    try {
                        MethodUseLog methodUseLog = new MethodUseLog();
                        methodUseLog.setMethodId(methodId);
                        methodUseLog.setMethodParam(JSONUtil.toJsonStr(data));
                        methodUseLog.setMethodName(combatMethod.getMethodName());
                        methodUseLog.setMethodResult(post.body());
                        methodUseLog.setCreateTime(new Date());
                        iMethodUseLogService.insertMethodUseLog(methodUseLog);
                        Long methodNum = combatMethod.getMethodNum();
                        if (methodNum == null) {
                            methodNum = 0L;
                        }
                        methodNum = methodNum + 1;
                        combatMethod.setMethodNum(methodNum);
                        iCombatMethodService.updateCombatMethod(combatMethod);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return post.body();
                } else {
                    HttpResponse post = HttpRequest.post(url)
                            .header("Authorization", basicAuthHeader)
                            .execute();
                    try {
                        MethodUseLog methodUseLog = new MethodUseLog();
                        methodUseLog.setMethodId(methodId);
                        methodUseLog.setMethodParam(JSONUtil.toJsonStr(data));
                        methodUseLog.setMethodName(combatMethod.getMethodName());
                        methodUseLog.setMethodResult(post.body());
                        methodUseLog.setCreateTime(new Date());
                        iMethodUseLogService.insertMethodUseLog(methodUseLog);
                        Long methodNum = combatMethod.getMethodNum();
                        if (methodNum == null) {
                            methodNum = 0L;
                        }
                        methodNum = methodNum + 1;
                        combatMethod.setMethodNum(methodNum);
                        iCombatMethodService.updateCombatMethod(combatMethod);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return post.body();
                }
            }
            return null;
        }
        return null;
    }


    /**
     * 根据算法id调用算法，立即返回结果
     *
     * @param methodId
     * @return
     */
    public Map<String, Object> methodUser(Long methodId, Map<String, Object> requestBody) {
        CombatMethod combatMethod = iCombatMethodService.selectCombatMethodById(methodId);
        if (combatMethod != null) {
            String url = combatMethod.getMethodUrl();
            if (StringUtils.isNotBlank(url)) {
//                Map<String, Object> result = postForObject(requestBody, url);
                Map<String, Object> result = postForObject(requestBody, MediaType.APPLICATION_FORM_URLENCODED, url);
                return result;
            }
            return null;
        }
        return null;
    }


    public Map<String, Object> postForObject(Map<String, Object> requestBody, String apiPath) {
        if (requestBody == null || requestBody.size() == 0)
            return null;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 发送post请求，并打印结果，以String类型接收响应结果JSON字符串
        LinkedHashMap result = restTemplate.postForObject(apiPath, requestBody, LinkedHashMap.class);
        return result;
//        return null;
    }

    public Map<String, Object> postForObject(Map<String, Object> requestBody, MediaType mediaType, String apiPath) {
        if (requestBody == null || requestBody.size() == 0)
            return null;
        String jsonStr1 = JSONUtil.toJsonStr(requestBody.get("data"));
        //发送post请求，并打印结果，以String类型接收响应结果JSON字符串
        String post = HttpUtil.post(apiPath, jsonStr1);
        LinkedHashMap bean = JSONUtil.toBean(post, LinkedHashMap.class);
        return bean;
//        return null;
    }

    public List<Map> methodUse(Long methodId, String data) {
        String result = "";
        CombatMethod combatMethod = iCombatMethodService.selectCombatMethodById(methodId);
        if (combatMethod != null) {
            String url = combatMethod.getMethodUrl();
            if (StringUtils.isNotBlank(url) && "POST".equals(combatMethod.getMethodType())) {

                HttpResponse response = HttpRequest.post(url).header("Content-Type", "application/json")
                        .body(data) // 设置请求体
                        .execute(); // 执行请求

                if (response.isOk()) {
                    System.out.println("Response: " + response.body());
                } else if (response.getStatus() == 307) {
                    String location = response.header("Location"); // 获取重定向地址
                    System.out.println("Redirected to: " + location);
                    // 可以选择再次发送请求到新的位置
                    HttpResponse redirectedResponse = HttpRequest.post(location).header("Content-Type", "application/json")
                            .body(data) // 重新设置请求体（如果需要）
                            .execute();
                    System.out.println("Redirected Response: " + redirectedResponse.body());
                    result = redirectedResponse.body();
                    List<Map> bean = JSONUtil.toList(result, Map.class);
                    return bean;
                } else {
                    System.out.println("Error: " + response.getStatus());
                }

            }
        }

        return null;
    }
}
